package com.ddiviewer;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Calendar;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.os.Handler;
import android.util.Log;
import android.view.View;

/*
 * Thread to control main event loop
 */
class MainThread extends Thread {
	
	View			v;
	String			results;
	String			nameonly;
	String			searchUrl;
	Handler			h;
	String[]		tabs;
	String			keyword;
	
	
	/*
	 * Constructor - MainThread
	 */
	public MainThread (View v, Handler h, String searchUrl, String keyword, String nameonly) {
		this.v			= v;
		this.h			= h;
		this.nameonly	= nameonly;
		this.searchUrl	= searchUrl;
		this.keyword	= keyword;
		tabs			= v.getContext().getResources().getStringArray(R.array.tabs);
	}
	
	/*
	 * Override run method
	 */ 
	@Override
	public void run() {
		// Heavy Duty stuff goes here!
		try {
			Connection c 			= new Connection();
			SAXParserFactory spf	= SAXParserFactory.newInstance();
			spf.setValidating(false);
			SAXParser sp			= spf.newSAXParser();
			XMLReader xmlr			= sp.getXMLReader();
			DDIXMLHandler ddixmlp 	= new DDIXMLHandler();
			xmlr.setContentHandler(ddixmlp);


			Log.d("DEBUG", nameonly);
			Log.d("DEBUG", keyword + "-" + nameonly + ".zip");
			
			File cacheFile = new File(v.getContext().getCacheDir(), "" + keyword + "-" + nameonly + ".zip");
			Log.d("RESULTS_FILE_NAME", cacheFile.getAbsolutePath());
			
			if (!cacheFile.exists() || !(cacheFile.lastModified() > ((Calendar.getInstance().getTimeInMillis()/1000) - (60*60*24*7)))) {

				ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(cacheFile));
				OutputStreamWriter osw;
				try {

    				zos.setLevel(Deflater.BEST_COMPRESSION);

					// Perform the search
					for (int i = 0; i < tabs.length; i++) {
						String result = new String();
						result = c.connect(searchUrl, tabs[i], keyword, nameonly, v); //Filenames of XML data
						zos.putNextEntry(new ZipEntry(tabs[i]));
	    				osw = new OutputStreamWriter(zos);
	    				osw.write(result);
	    				osw.flush();
					}
    			} catch (Exception e) {
    				Log.e("EXCEPTION", e.getMessage());
    			} finally {
    				try {
    					zos.close();
    				} catch (Exception e) {
    					Log.e("EXCPETION", e.getMessage());
    				}
    			}
			} else {
				Log.d("CACHEFILE", "VALID CACHE, NOT RETRIEVING DATA");
			}

			ZipFile zf = new ZipFile(cacheFile);
			ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(cacheFile)));
			ZipEntry entry;
			while ((entry = zis.getNextEntry()) != null) {
				InputStream is = zf.getInputStream(entry);
				xmlr.parse(new InputSource(new InputStreamReader(is)));
			}

			h.sendEmptyMessage(1);
		} catch (Exception e) { 
			Log.e("DDIViewer - Run Exception", e.getMessage() + " " + e.getCause());
		}
	}

}